/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Huella.java
 *
 * Created on 10-feb-2013, 17:42:03
 */
package sisvoto.vista;

import SecuGen.FDxSDK.jni.FDxError;
import SecuGen.FDxSDK.jni.JFPLib;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import sisvoto.DAO.ConsultasBD;
import sisvoto.ModeloDAO.HuellaDactilarDAO;
import sisvoto.Utiles.Mensajes;
import sisvoto.modelo.Elector;

/**
 *
 * @author Dianita
 */
public class RegistrarHuella extends javax.swing.JDialog {

    JFPLib jplib = null;
    Elector elector;
    BufferedImage img1gray;
    byte[] imageBuffer1;
    private byte[] regMin1 = new byte[400];
    sisvoto.modelo.HuellaDactilar huellaupdate;

    /** Creates new form Huella */
    public RegistrarHuella(java.awt.Frame parent, boolean modal, Elector elector) {
        super(parent, modal);
        this.elector = elector;
        initComponents();
        fijarelector();
        new Mensajes().StandarTick(this, "Éste elector posee registradas: " + validarHuellas(elector) + " huellas");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        imagePanel1 = new com.mycsistemas.swingec.panel.ImagePanel();
        jLblAdmElector = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        jLblCedulaElector1 = new javax.swing.JLabel();
        txtcedula = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        lblImagen = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLblCedulaElector2 = new javax.swing.JLabel();
        txtApellido = new javax.swing.JTextField();
        jcbDedo = new javax.swing.JComboBox();
        jLblCedulaElector4 = new javax.swing.JLabel();
        jLblCedulaElector5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Huella Dactilar");
        setAlwaysOnTop(true);

        imagePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/''_10102012_1738.jpeg"))); // NOI18N
        imagePanel1.setLayout(null);

        jLblAdmElector.setFont(new java.awt.Font("Georgia", 3, 18));
        jLblAdmElector.setForeground(new java.awt.Color(255, 255, 255));
        jLblAdmElector.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLblAdmElector.setText("Huella Dactilar");
        imagePanel1.add(jLblAdmElector);
        jLblAdmElector.setBounds(100, 30, 220, 21);

        txtNombres.setEditable(false);
        imagePanel1.add(txtNombres);
        txtNombres.setBounds(110, 150, 250, 30);

        jLblCedulaElector1.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblCedulaElector1.setForeground(new java.awt.Color(255, 255, 255));
        jLblCedulaElector1.setText("Cédula:");
        imagePanel1.add(jLblCedulaElector1);
        jLblCedulaElector1.setBounds(30, 70, 100, 30);

        txtcedula.setEditable(false);
        imagePanel1.add(txtcedula);
        txtcedula.setBounds(110, 70, 250, 30);

        lblImagen.setToolTipText("Huella Dactilar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblImagen, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblImagen, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
        );

        imagePanel1.add(jPanel1);
        jPanel1.setBounds(20, 260, 200, 200);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/DeleteRed.png"))); // NOI18N
        jButton2.setText("Salir");
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        imagePanel1.add(jButton2);
        jButton2.setBounds(250, 400, 110, 60);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/huella.gif"))); // NOI18N
        jButton3.setText("Capturar");
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        imagePanel1.add(jButton3);
        jButton3.setBounds(250, 260, 110, 60);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/save_32.png"))); // NOI18N
        jButton4.setText("Guardar");
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        imagePanel1.add(jButton4);
        jButton4.setBounds(250, 330, 110, 60);

        jLblCedulaElector2.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblCedulaElector2.setForeground(new java.awt.Color(255, 255, 255));
        jLblCedulaElector2.setText("Apellidos:");
        imagePanel1.add(jLblCedulaElector2);
        jLblCedulaElector2.setBounds(30, 110, 100, 30);

        txtApellido.setEditable(false);
        imagePanel1.add(txtApellido);
        txtApellido.setBounds(110, 110, 250, 30);

        jcbDedo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Índice Derecho", "Índice Izquierdo" }));
        imagePanel1.add(jcbDedo);
        jcbDedo.setBounds(110, 200, 250, 30);

        jLblCedulaElector4.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblCedulaElector4.setForeground(new java.awt.Color(255, 255, 255));
        jLblCedulaElector4.setText("Dedo:");
        imagePanel1.add(jLblCedulaElector4);
        jLblCedulaElector4.setBounds(30, 200, 100, 30);

        jLblCedulaElector5.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblCedulaElector5.setForeground(new java.awt.Color(255, 255, 255));
        jLblCedulaElector5.setText("Nombres:");
        imagePanel1.add(jLblCedulaElector5);
        jLblCedulaElector5.setBounds(30, 150, 100, 30);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    dispose();
}//GEN-LAST:event_jButton2ActionPerformed

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
    HuellaDactilarDAO hdao;

    if (huellasxistentes(jcbDedo.getSelectedItem().toString())) {
        if (imageBuffer1 != null) {
            sisvoto.modelo.HuellaDactilar hd = new sisvoto.modelo.HuellaDactilar();
            hd.setDedo(jcbDedo.getSelectedItem().toString());
            hd.setElector(elector);
            hd.setHuella(regMin1);
            hdao = new HuellaDactilarDAO(hd);
            try {
                hdao.persist();
                new Mensajes().StandarTick(this, "Guardado Exitosamente");
            } catch (Exception ex) {
                System.out.println(ex);
                new Mensajes().StandarWarning(this, "No se pudo Guardar");
            }
        }
    } else {
        if (new Mensajes().ConfirmacionDialogowarning(this, "Ya ha Registrado Esta Huella.\n ¿Desea Actualizar el Registro? ") == 0) {
            huellaupdate.setHuella(regMin1);
            hdao = new HuellaDactilarDAO(huellaupdate);
            try {
                hdao.update();
                new Mensajes().StandarTick(this, "Actualizado Exitosamente");
            } catch (Exception ex) {
                System.out.println(ex);
                new Mensajes().StandarWarning(this, "No se pudo Guardar");
            }
        }

    }

}//GEN-LAST:event_jButton4ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
    this.img1gray = new BufferedImage(260, 300, BufferedImage.TYPE_BYTE_GRAY);
    this.imageBuffer1 = ((java.awt.image.DataBufferByte) img1gray.getRaster().getDataBuffer()).getData();
    this.jplib = Configuracionfinger.getFplib();
    if (jplib != null) {
        long ret;
        ret = this.jplib.getImage(imageBuffer1);
        jplib.getMinutiae(imageBuffer1, regMin1);
        if (ret == FDxError.ERROR_NONE) {
            this.lblImagen.setIcon(new ImageIcon(img1gray));
            new Mensajes().StandarTick(this, "Huella Capturada");
        } else {
            new Mensajes().StandarWarning(this, "No se pudo Obtener la Imagen");
            jplib.resetDevice();
        }
    } else {
        if (Principal.sesion.getUsuario().getIdPrivilegio().getAcceso().equals("TOTAL")) {
            new Mensajes().StandarWarning(this, "        La Conexión Con el Dispositivo \n No Ha Sido Inicializada. Intente Nuevamente");
            Configuracionfinger cf = new Configuracionfinger(null, true);
            cf.setLocationRelativeTo(this);
            cf.setVisible(true);
        }else{
            new Mensajes().StandarWarning(this, "        La Conexión Con el Dispositivo No Ha Sido Inicializada. \n            Consulte Con el Administrador");
        }
    }
}//GEN-LAST:event_jButton3ActionPerformed
    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.mycsistemas.swingec.panel.ImagePanel imagePanel1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLblAdmElector;
    private javax.swing.JLabel jLblCedulaElector1;
    private javax.swing.JLabel jLblCedulaElector2;
    private javax.swing.JLabel jLblCedulaElector4;
    private javax.swing.JLabel jLblCedulaElector5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JComboBox jcbDedo;
    private javax.swing.JLabel lblImagen;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JTextField txtNombres;
    private javax.swing.JTextField txtcedula;
    // End of variables declaration//GEN-END:variables

    private void fijarelector() {
        txtcedula.setText(elector.getCedula());
        txtNombres.setText(elector.getNombre());
        txtApellido.setText(elector.getApellido());
    }

    private int validarHuellas(Elector elector) {
        ArrayList<sisvoto.modelo.HuellaDactilar> huellas = (ArrayList<sisvoto.modelo.HuellaDactilar>) new ConsultasBD().buscarPOR("HuellaDactilar", "elector", "'" + elector.getId() + "'");
        if (huellas.size() == 2) {
            return 2;
        }
        if (huellas.size() == 1) {
            return 1;
        }
        if (huellas.isEmpty()) {
            return 0;
        }
        return -1;
    }

    private boolean huellasxistentes(String dedo) {
        ArrayList<sisvoto.modelo.HuellaDactilar> huellas = (ArrayList<sisvoto.modelo.HuellaDactilar>) new ConsultasBD().buscarPOR2("HuellaDactilar", "elector", "'" + this.elector.getId() + "'", "dedo", "'" + dedo + "'");
        if (huellas.isEmpty()) {
            return true;
        } else {
            huellaupdate = huellas.get(0);
            return false;
        }
    }
}
